package com.es.controller;

import com.alibaba.fastjson.JSONObject;
import com.es.bean.ESData;
import com.es.bean.User;
import com.es.service.ElasticsearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2022/11/21 14:54
 */
@RestController
@Slf4j
public class EsController {


    @Autowired
    private ElasticsearchService service;

    /**
     * {{localhost}}/es/add2es
     * {
     * "data":{
     * "name":"sensetime",
     * "sex":"1",
     * "age":18
     * },
     * "indexName":"",
     * "id":"12"
     * }
     *
     * @param data
     * @return
     */
    @PostMapping(value = "/add2es")
    public String add2ES(@RequestBody ESData data) {
        return service.add_v2(data.getData(), data.getIndexName(), data.getId());
    }

    /**
     * {{localhost}}/es/getFromEs
     * <p>
     * {
     * "data":{
     * "name":"sensetime",
     * "sex":"1",
     * "age":18
     * },
     * "indexName":"",
     * "id":"12"
     * }
     *
     * @param data
     * @return
     */
    @GetMapping(value = "/getFromEs")
    public User getFromES(@RequestBody ESData data) {
        return JSONObject.parseObject(service.get_v2(null, data.getId()), User.class);
    }


    @GetMapping(value = "/searchByCondition")
    public List<User> searchByCondition(@RequestBody ESData data) throws Exception {
        List<String> res = service.searchByCondition(data.getIndexName(), data.getData());
        List<User> ans = new ArrayList<>();
        if (CollectionUtils.isEmpty(res)) {
            return ans;
        }
        for (String item : res) {
            ans.add(JSONObject.parseObject(item, User.class));
        }
        return ans;
    }


}
